package belf.migrate.engine.verify;

import belf.migrate.api.model.VerifyModel;
import belf.migrate.api.type.DbObjectType;
import belf.migrate.engine.job.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import spark.Request;
import spark.Response;

@Slf4j
public class VerifyHandler {

    private static Gson gson = new Gson();
    public static JsonObject verify(Request request, Response response) {

        // 设置响应类型为JSON
        response.type("application/json");
        // 获取请求体中的JSON数据并反序列化为Job对象
        ObjectMapper mapper = new ObjectMapper();
        try {
            VerifyModel verifyModel = mapper.readValue(request.body(), VerifyModel.class);
            DbObjectType dbObjectType = DbObjectType.getDbObjectType(verifyModel.getTaskTypeScope());
            switch (dbObjectType) {
                case TABLE:
                    return VerifyTable.verify(verifyModel);
                case VIEW:
                    return VerifyView.verify(verifyModel);
                case FUNCTION:
                    return VerifyFunction.verify(verifyModel);
                case PROCEDURE:
                    return VerifyProcedure.verify(verifyModel);
                case TRIGGER:
                    return VerifyTrigger.verify(verifyModel);
                case SEQUENCE:
                    return VerifySequence.verify(verifyModel);
                case TYPE:
                    return VerifyType.verify(verifyModel);
            }

        } catch (JsonProcessingException e) {
            log.error("解析参数格式错误");
            JsonObject jsonResponse = new JsonObject();
            jsonResponse.addProperty("code", 11);
            jsonResponse.addProperty("message", "解析请求的json格式失败");
            return jsonResponse;
        }
        return gson.toJsonTree(Result.fail("校验失败！")).getAsJsonObject();
    }
}
